package com.atguigu.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author zhangchunsheng
 * @CreateTime: 2024/12/31
 */
public class JdbcUtils {

    private static DataSource dataSource;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    static {
        try {
            Properties properties = new Properties();
            properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Author: zhangchunsheng
     * @Date: 2024/12/31 15:19
     * 获取Connection对象
     */
    public static Connection getConnection() throws SQLException {
        //从ThreadLocal中获取Connection对象
        Connection connection = threadLocal.get();
        //第一次获取Connection对象,Connection是null
        if (connection == null) {
            //从连接池中获取Connection对象
            connection = dataSource.getConnection();
            //将Connection对象存入ThreadLocal中
            threadLocal.set(connection);
        }
        return connection;
    }

    /**
     * @Author: zhangchunsheng
     * @Date: 2024/12/31 15:21
     * 关闭Connection对象
     */
    public static void closeConnection() throws SQLException{
        Connection connection = threadLocal.get();
        if (connection != null) {
            //关闭Connection对象
            connection.close();
            //从ThreadLocal中移除Connection对象
            threadLocal.remove();
        }
    }

}
